package controller;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.UserModel;

import dao.User;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doProcess(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			NoSuchAlgorithmException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		User user_dao = new User();
		String userName = request.getParameter("un");
		String password = request.getParameter("upd");
		UserModel user = user_dao.Login(userName, password);
		HttpSession session = request.getSession();
		if (user != null) {
			
			if(user.isRole() == false){
				session.setAttribute("nguoidung", user);
				response.sendRedirect("LoadProducts");
				return;
			}
			session.setAttribute("user_session", user);
		} else {
			session.setAttribute("alert",
					"<div class=\"alert alert-error\">Tài khoản không hợp lệ!</div>");
		}
		response.sendRedirect("./");

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			doProcess(request, response);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			doProcess(request, response);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

}
